#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <time.h>
#include "tlpi.h"


/* error peocess */
void
errExit(char *info)
{
	perror(info);
	exit(-1);
}

void
fatal(char *info)
{
	fprintf(stderr, "%s\n", info);
	exit(-1);
}

/* time function */
char *
curTime(const char *fmt)
{
	static char buf[BUF_SIZE];
	time_t t;
	size_t s;
	struct tm *tm;

	t = time(NULL);
	tm = localtime(&t);
	if(tm == NULL)
		return NULL;

	s = strftime(buf, BUF_SIZE, (fmt != NULL)? fmt : "%c", tm);

	return (s == 0)? NULL : buf;
}

/* file lock functions */
int lockReg(int fd, int cmd, int type, int whence, int start, int len)
{
	struct flock fl;

	fl.l_type = type;
	fl.l_whence = whence;
	fl.l_start = start;
	fl.l_len = len;

	return fcntl(fd, cmd, &fl);
}

int lockRegion(int fd, int type, int whence, int start, int len)
{
	return lockReg(fd, F_SETLK, type, whence, start, len);
}

int lockRegionWait(int fd, int type, int whence, int start, int len)
{
	return lockReg(fd, F_SETLKW, type, whence, start, len);
}

pid_t isRegionLockable(int fd, int type, int whence, int start, int len)
{
	struct flock fl;

	fl.l_type = type;
	fl.l_whence = whence;
	fl.l_start = start;
	fl.l_len = len;

	if(fcntl(fd, F_GETLK, &fl) == -1)
		return -1;

	return (fl.l_type == F_UNLCK)? 0 : fl.l_pid;
}
